//
//  LoginNewViewController.m
//  IpadTestB
//
//  Created by edianzu on 2017/6/26.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "LoginNewViewController.h"
#import "ReloadDataViewController.h"
@interface LoginNewViewController ()<UITextFieldDelegate>

@end

@implementation LoginNewViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor purpleColor];
    [self creatUI];
}

-(void)creatUI{
    UIImageView * img = [[UIImageView alloc]init];//背景
    img.image = [UIImage imageNamed:@"loginBack"];
    [self.view addSubview:img];
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(self.view);
    }];
    //两个依赖VIEW
    _userNameView = [[UIView alloc]init];
    _userNameView.backgroundColor = [UIColor whiteColor];
    _userNameView.layer.cornerRadius = 10;
    [self.view addSubview:_userNameView];
    [_userNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).with.offset(350*AutoScaleVertical);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(400*AutoScaleHorizontal, 50*AutoScaleVertical));
    }];
    _passWordView = [[UIView alloc]init];
    _passWordView.backgroundColor = [UIColor whiteColor];
    _passWordView.layer.cornerRadius = 10;
    [self.view addSubview:_passWordView];
    [_passWordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_userNameView.mas_bottom).with.offset(20*AutoScaleVertical);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(400*AutoScaleHorizontal, 50*AutoScaleVertical));
    }];
    //两个图片以及分割线
    _userNameImage = [[UIImageView alloc]init];
    _userNameImage.image = [UIImage imageNamed:@"loginUser"];
    [_userNameView addSubview:_userNameImage];
    [_userNameImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_userNameView.mas_left).with.offset(10*AutoScaleHorizontal);
        make.centerY.mas_equalTo(_userNameView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(25*AutoScaleHorizontal, 25*AutoScaleVertical));
    }];
    
    _passWordImage = [[UIImageView alloc]init];
    _passWordImage.image = [UIImage imageNamed:@"loginPassword"];
    [_passWordView addSubview:_passWordImage];
    [_passWordImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_passWordView.mas_left).with.offset(10*AutoScaleHorizontal);
        make.centerY.mas_equalTo(_passWordView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(25*AutoScaleHorizontal, 25*AutoScaleVertical));
    }];
    
    _userNameLineView = [[UIView alloc]init];
    _userNameLineView.backgroundColor = [HexColor colorWithHexString:@"#d2d2d2"];
    [_userNameView addSubview:_userNameLineView];
    [_userNameLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_userNameImage.mas_right).with.offset(10*AutoScaleHorizontal);
        make.centerY.mas_equalTo(_userNameView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(1*AutoScaleHorizontal, 27*AutoScaleVertical));
    }];
    
    _passWordLineView = [[UIView alloc]init];
    _passWordLineView.backgroundColor = [HexColor colorWithHexString:@"#d2d2d2"];
    [_passWordView addSubview:_passWordLineView];
    [_passWordLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_passWordImage.mas_right).with.offset(10*AutoScaleHorizontal);
        make.centerY.mas_equalTo(_passWordView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(1*AutoScaleHorizontal, 27*AutoScaleVertical));
    }];
    
    //两个输入框
    _userNameText = [[UITextField alloc]init];
    _userNameText.delegate = self;
    _userNameText.placeholder = @"输入用户名";
//        _userNameText.text = @"su61010001";
    //    _userNameText.backgroundColor = [UIColor purpleColor];
    [_userNameView addSubview:_userNameText];
    [_userNameText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_userNameLineView.mas_right).with.offset(10*AutoScaleHorizontal);
        make.centerY.mas_equalTo(_userNameLineView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(300*AutoScaleHorizontal, 40*AutoScaleVertical));
    }];
    
    _passWordText = [[UITextField alloc]init];
    _passWordText.delegate = self;
    _passWordText.placeholder = @"密码";
    _passWordText.secureTextEntry = YES;
//        _passWordText.text = @"123456";
    //    _passWordText.backgroundColor = [UIColor purpleColor];
    [_passWordView addSubview:_passWordText];
    [_passWordText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_passWordLineView.mas_right).with.offset(10*AutoScaleHorizontal);
        make.centerY.mas_equalTo(_passWordLineView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(300*AutoScaleHorizontal, 40*AutoScaleVertical));
    }];
    
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginBtn.backgroundColor = UIColorFromRGB(246, 180, 90);
    _loginBtn.layer.cornerRadius =10;
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    _loginBtn.titleLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
    [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_loginBtn addTarget:self action:@selector(pressLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginBtn];
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_passWordView.mas_bottom).with.offset(60*AutoScaleVertical);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(280*AutoScaleHorizontal, 40*AutoScaleVertical));
    }];
    
    
    //添加键盘监听事件
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}


#pragma mark ---- 根据键盘高度将当前视图向上滚动同样高度
///键盘显示事件
- (void)keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
    CGFloat offset = kbHeight;
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //将视图上移计算好的偏移
    if(offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.view.frame = CGRectMake(0.0f, -100*AutoScaleVertical, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}
#pragma mark ---- 当键盘消失后，视图需要恢复原状
///键盘消失事件
- (void)keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}
// 释放
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

#pragma mark  登陆
-(void)pressLogin{
    
    if (_userNameText.text.length ==0) {
        [self showMessage:@"用户名不能为空"];
    }else if (_passWordText.text.length ==0){
        [self showMessage:@"密码不能为空"];
    }else{
    NSLog(@"开始登陆");
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookieArray = [NSArray arrayWithArray:[cookieJar cookies]];
    for (NSHTTPCookie *obj in cookieArray) {
        //        NSLog(@"现在的COOKIE %@",obj);
        [cookieJar deleteCookie:obj];
        
    }
    //检测网络
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    //    AFNetworkReachabilityStatusUnknown          = -1,
    //    AFNetworkReachabilityStatusNotReachable     = 0,
    //    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    //    AFNetworkReachabilityStatusReachableViaWiFi = 2,
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown || manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        [self showMessage:@"当前网络状态不佳，请检验"];
    }else{
        //菊花
        self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
        //    _HUD.mode = MBProgressHUDModeIndeterminate;
        //     _HUD.opacity = 1;
        self.HUD.color = [UIColor whiteColor];
        self.HUD.dimBackground = YES;
        //设置菊花颜色  只能设置菊花的颜色
        self.HUD.activityIndicatorColor = [UIColor redColor];
        [self.view addSubview:self.HUD];
        [self.HUD showAnimated:YES];
        NSString * urls = @"/authenticate/credentials";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSDictionary *parama = @{@"Username":_userNameText.text,@"Password":_passWordText.text};
        [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
            NSLog(@"请求成功");
            NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
            
            if (![[user objectForKey:@"UserName"]isEqualToString:_userNameText.text]) {
                [user removeObjectForKey:@"AllData"];
            }//换号清除数据
            
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            //NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
            //NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSDictionary * dic = dict[@"Meta"];
            if ([dic[@"RoleType"] isEqualToString:@"7"]) {
                NSLog(@"登陆成功");
                NSString * companyName = dic[@"RealName"];
                [user setObject:companyName forKey:@"companyName"];
                NSLog(@"%@",companyName);
                
                [user setObject:dic[@"AgencyId"] forKey:@"AgencyId"];
                [user setObject:_userNameText.text forKey:@"UserName"];
                [user setObject:_passWordText.text forKey:@"PassWord"];
                NSString * isLogin = @"isLogin";
                [user setObject:isLogin forKey:@"isLogin"];
                [user synchronize];
                [self showMessage:@"登陆成功"];
            
                ReloadDataViewController * rvc = [[ReloadDataViewController alloc]init];
                UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:rvc];
                navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
                navi.navigationBar.translucent = NO;
                [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
                [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
                [self.navigationController presentViewController:navi animated:YES completion:nil];
            }else{
                UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"帐号类型错误" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alc addAction:act];
                [self presentViewController:alc animated:YES completion:nil];
            }
            
            
        } failure:^(NSError *error) {
            UIAlertController * alc = [UIAlertController alertControllerWithTitle:@"提示" message:@"帐号或密码错误" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alc addAction:act];
            [self presentViewController:alc animated:YES completion:nil];
            NSError * err = error;
            NSLog(@"登陆因为这个失败了%@",err.description);
            [self.HUD removeFromSuperview];
            self.HUD = nil;
            
            
        }];
    }

    }
}

#pragma mark  清除键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return [textField resignFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES]; //实现该方法是需要注意view需要是继承UIControl而来的
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
